<?php

namespace App\Http\Controllers\PhpCookBook\Arr;

use App\BCAM\CMVariable\CMVariable;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Debug\Dumper;

/**
 * 数组构建
 * Class StructureController
 * @package App\Http\Controllers\PhpCookBook\Arr
 */
class StructureController extends Controller
{
    private $appKey;
    private $fruits;
    private $animals;
    public function __construct()
    {
        $this->appKey = getenv('APP_KEY');
        $this->fruits = ['apple','banana','coconut'];
        $this->animals = ['apple','banana','coconut'];
    }

    /* 4.6 改变数组的大小 */
    public function arrayPad(){
        //起初 3元素
        $array = $this->fruits;

        //增加到5个
        $arrayUp = array_pad($array,5,' ');

        $arrayDn = array_slice($array,2);

        $this->compareRes($array,$arrayUp,$arrayDn);
    }

    /* 4.7 将数组追加到另一个数组 */
    public function arrayMerge(){
        //索引数组
        $fruits = collect($this->fruits);
        $animals = collect($this->animals);
        //索引数组
        $merageArr = array_merge($this->fruits,$this->animals);
        $merageCol = $fruits->merge($animals);
        /* 合并只使用数值建的数组是,数组将[重新编号]*/
        $this->compareRes($merageArr,$merageCol->all());
        $this->fruits['temp'] = 'pear';
        $fruits['temp'] = 'pear';
        $this->animals['temp'] = 'king kong';
        $animals['temp'] = 'king kong';

        /* 合并使用字符串数组时,若有重复键名,后面的数组会覆盖重复键名的值(相当于往前移了),有数字又有字符串时,两种行为都会提现*/
        $merageArrO = array_merge($this->fruits,$this->animals);
        $merageColO = $fruits->merge($animals);
        $this->compareRes($merageArrO,$merageColO->all());
    }

    /* 4.7 将数组追加到另一个数组 */
    public function arrayPlus(){
        //+ 操作符也可以用来合并数组,对于同名的键,会使用[左边]的值.[不会重新排序]
        //没有减号操作
        $newArr = $this->fruits + $this->animals;

        //因为左右两个数组的键名都冲突了,全保留了左边fruits的值
        $this->compareRes($newArr);
    }
    private function compareRes(...$args){
        extract($args,EXTR_PREFIX_ALL,'variable');
        $arrKey = array_keys($args);
        $string = join(',$variable_',$arrKey);
        //需要命名空间
        //都可以实现
        //eval('App\BCAM\CMVariable\CMVariable::compareRes($variable_'.$string.");");
        eval("App\BCAM\CMVariable\CMVariable::compareRes(\$variable_$string);");
    }

}
